# -*- coding:utf-8 -*-
# business/main_business.py

from sanic.log import logger
from sqlalchemy import select

from model.model_result import DataResult
from model.models import MainBusiness


async def get_main_business(request):
    """
    获取主体业务列表
    """
    data_result = DataResult()
    session = request.ctx.session
    try:
        main_busi_list = []
        async with session.begin():
            query_main_busi = select(MainBusiness).where(MainBusiness.is_deleted == 0)
            result = await session.execute(query_main_busi)
            main_busi_objs = result.scalars().all()
            main_busi_list = [v.to_dict() for v in main_busi_objs]
            logger.debug(f"get main_business: {main_busi_list}")
        data_result.data["items"] = main_busi_list
        data_result.message = "获取主体业务列表成功"
    except Exception as ex:
        data_result.status = False
        data_result.code = 400
        data_result.message = "获取主体业务列表失败"
        logger.exception(ex)
    return data_result


async def get_main_business_detail_by_id(main_busi_id, request):
    """
    根据ID查询主体业务详情
    """
    if not main_busi_id:
        raise Exception('缺少主体业务ID(main_busi_id)参数值!')
    data_result = DataResult()
    session = request.ctx.session
    try:
        main_busi_info = {}
        async with session.begin():
            query_main_busi = select(
                MainBusiness
            ).where(
                MainBusiness.is_deleted == 0,
                MainBusiness.main_business_id == main_busi_id
            )
            result = await session.execute(query_main_busi)
            main_busi_obj = result.scalar()
            main_busi_info = main_busi_obj.to_dict()
            logger.debug(f"get main_business info by id {main_busi_id}, res: {main_busi_info}")
        data_result.data = main_busi_info
        data_result.message = "根据ID查询主体业务详情成功"
    except Exception as ex:
        data_result.status = False
        data_result.code = 400
        data_result.message = "根据ID查询主体业务详情失败"
        logger.exception(ex)
    return data_result
